/*   KONVE     Convert utility ST-xx  -> FITS   
     Copyright (C) 1997  Filip Hroch, Masaryk University, Brno, CZ

     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation; either version 2 of the License, or
     (at your option) any later version.

     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program; if not, write to the Free Software
     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

    E-mail: hroch@physics.muni.cz
    Web:    http://www.sci.muni.cz/~hroch/index.html
    Postal address: F.Hroch
                    Department of Theoretical Physics and Astrophysics
                    Masaryk University
                    Kotlarska 2
                    611 37 Brno
                    Czech Republic
*/

/**********************  main program *****************/

#include "konve.h"
#include <stdio.h>
#include <stdlib.h>

#define MAXLINE    250     /* length of text line */
#define MAXFORMAT    5

char CType[MAXTYPE][30] =
 { "ST-4X Image",                          /* 0 */
   "ST-4X Compressed Image",               /* 1 */
   "ST-5 Image",                           /* 2 */
   "ST-5 Compressed Image",                /* 3 */
   "ST-6 Image",                           /* 4 */
   "ST-6 Compressed Image",                /* 5 */
   "ST-7 Image",                           /* 6 */
   "ST-7 Compressed Image",                /* 7 */
   "ST-8 Image",                           /* 8 */
   "ST-8 Compressed Image",                /* 9 */
/*
 *  added two file types by Miroslav Broz,
 *  miroslav.broz@usa.net, Nov 24th 1998
 */
   "PixCel255 Image",                      /* 10 */
   "PixCel255 Compressed Image" };         /* 11 */


main ( argc, argv )
int argc;
char *argv[];
{
int konv(),pos(),copy(),endpos(),i,j,l,n,icit,stdinput = 0, head = 0;
long tcor;
char dirname[MAXLINE] = "", parname[MAXLINE] = "";
char line[MAXLINE],buf1[MAXLINE],mask[MAXLINE] = "kout????.fts";
FILE *fopen(), *fp;
static char format[MAXFORMAT][5] = { "","%01d", "%02d", "%03d", "%04d" };

icit = 1;
tcor = 0L;

for( i = 1; i < argc; i++) {              /* loop over all parameters */
  if( (j = endpos(argv[i],"@")) != -1 ) {                 /* dir file */
    sscanf(argv[i]+j,"%s",dirname);
    if( dirname[0] == '\0' ) stdinput = 1; }
  if( (j = endpos(argv[i],"par=")) != -1 )          /* parameter file */
    sscanf(argv[i]+j,"%s",parname);
  if( (j = endpos(argv[i],"tcor=")) != -1 )        /* time correction */
    sscanf(argv[i]+j,"%ld",&tcor);
  if( (j = endpos(argv[i],"mask=")) != -1 )   /* mask of output files */
    sscanf(argv[i]+j,"%s",mask); 
  if( (j = endpos(argv[i],"-h")) != -1 ) head = 1;     /* only header */
}

if( (j = pos(mask,"*")) != -1 )                /* remove '*' wildcard */
  mask[j] = '?';
if( (j = pos(mask,"?")) != -1 )                      /* number of '?' */
  for( n = 0,l = j; mask[l] == '?' && n < MAXFORMAT-1; l++ )
     n = n + 1;
j = pos(mask,"?");

printf("KONVE Version 1.3, Copyright (C) 1998 F.Hroch, Masaryk University, Brno, CZ\n\r");
printf("Konve comes with ABSOLUTELY NO WARRANTY; This is free software, and you are\n\r");
printf("welcome to redistribute under certain conditions; see 'gnulic.doc' for details.\n\r\n\r");

if( dirname[0] != '\0' ) {                   /* images names read from file */
  if( (fp = fopen(dirname,"r")) == NULL ) {
    printf("Can't open file %s \n\r",dirname);
    exit(0); }
  while( fscanf(fp,"%s",line) != EOF ) {
    if( j != -1 ) {
      sprintf(buf1,format[n],icit);
      copy(buf1,n,mask+j); }
    if( konv(line,parname,tcor,mask,head) < 0 )
      printf("Can't convert file %s \n\r",line);
    icit = icit + 1;
  }
  fclose(fp);}
/* else */                         /* images names read from command line */
  for( i = 1; i < argc; i++)
    if( pos(argv[i],"=") == -1 && pos(argv[i],"@") == -1 
     && argv[i][0] != '-' ) {
      if( j != -1 ) {
      sprintf(buf1,format[n],icit);
      copy(buf1,n,mask+j);}
      if( konv(argv[i],parname,tcor,mask,head) < 0 )
      printf("Can't convert file %s \n\r",argv[i]);
      icit = icit + 1; }
/* else  */                        /* images names from standart input */
if( stdinput )
  while( gets(line) != NULL ) {
    if( j != -1 ) {
      sprintf(buf1,format[n],icit);
      copy(buf1,n,mask+j);}
    if( konv(line,parname,tcor,mask,head) < 0 )
      printf("Can't convert file %s \n\r",line);
    icit = icit + 1; }

if( argc > 1  && icit == 1 )
  printf("No input files.\n\r");

if( argc == 1 && icit == 1 ) {
  printf("KONVE        Convert utility ST-xx  ->  FITS\n\r\n\r");
  printf("Usage:konve [par=parfile] [tcor=?] [mask=?] [@dirfile] [image1] ...\n\r\n\r");
  printf("@dirfile= file with name(s) of image(s) to convert, no wildcards *,?\n\r");
  printf("          (for only '@', read image(s) name(s) from standart input)\n\r");
  printf("image1...= name(s) of simple image(s) to convert, no wildcards *,?\n\r");
  printf("par= parameter file\n\r");
  printf("tcor= correction of time in seconds\n\r");
  printf("mask= output mask (default = kout????.fts)\n\r");
  printf("-h = create only header of FITS file\n\r\n\r");
  printf("Example of parameter file:\n\r");
  printf("OBSERVER= 'J.WALKER'\n\r");
  printf("RA      =            90.0\n\r");
  printf("DEC     =            90.0\n\r");
  printf("EQUINOX =          2000.0\n\r");
}

}


/************************* Conversion ********************************/

int konv(name,parname,tcor,ftsname,head)
  char name[],parname[],ftsname[];
  long tcor;
  int head;
{
  FILE *STopen(),*FITScreate(),*fp,*fs;
  int i,n,ftype,nrow,value;
  int getSTrow(),putFITSrow(),FITSclose();
/*  unsigned char stbuf[STSIZE];*/
  unsigned char *stbuf;
  int endpos(),identify();

  printf("%s -> %s\n\r",name,ftsname);
  if( (fp = STopen(name,"rb")) == NULL ) {
      printf("Can't open the input file.\n\r");
      return(-1);
    }

  stbuf = malloc(HEADSIZE);
/* header of ST-xx file */
    if( (n = fread(stbuf,1,HEADSIZE,fp)) != HEADSIZE ) {
       printf("%d %d",n,HEADSIZE);
       printf("Can't read the head from the input file.\n\r");
       return(-1);
    }

/* identification of file type */
    if( (ftype = identify(stbuf)) < 0 ) {
      fclose(fp);
      return(-1);
    }

/* size */
   nrow = atol(stbuf+endpos(stbuf,"Width ="));
/*   if( 2*nrow > STSIZE ) {
     printf("Sorry, but I have shortly buffer then width of your image.\n\r");
     return(-1);
   }*/

/* create FITS file */
    if( (fs = FITScreate(ftsname,"wb",stbuf,parname,tcor)) == NULL ) {
      printf("Can't create FITS file.\n\r");
      fclose(fp);
      return(-1);
    }
   free(stbuf);

stbuf = malloc(2*nrow);
if( !head ) 
/* data conversion */
     while( (n = getSTrow(fp,stbuf,ftype,nrow)) != 0 ) {
       if( n == -1 ) {
         printf("Can't read the ST-xx file.\n\r");
         goto konec; }
        for( i = 0; i < 2*nrow; i = i + 2 ) {   
           value = *(stbuf + i) + 256* *(stbuf + i + 1);
           value = value - 100;               /* BIAS substract */
           *(stbuf + i + 1) = value/256;
           *(stbuf + i) = value - 256* *(stbuf + i + 1);
        }
        for( i = 0; i < nrow/2; i++ ) {   /* flipping */ 
/*         a[2*i]   <-> a[2*nrow - 2*i - 2]
           a[2*i+1] <-> a[2*nrow - 2*i - 1] */
           value = *(stbuf + 2*i);
           *(stbuf + 2*i) = *(stbuf + 2*(nrow - i) - 2);
           *(stbuf + 2*(nrow - i) - 2) = value;
           value = *(stbuf + 2*i + 1);
           *(stbuf + 2*i + 1) = *(stbuf + 2*(nrow - i) - 1);
           *(stbuf + 2*(nrow - i) - 1) = value;        
        }
       if( putFITSrow(fs,stbuf,nrow) != nrow ) {
         printf("Can't write data to the FITS file.\n\r");
         goto konec; }
       }

konec:
/* close files and return */
  free(stbuf);
  fclose(fp);
  if( FITSclose(fs) != FITSSIZE ) {
    printf("Can't close the FITS file.\n\r");
    return(-1);
  }
  return(1);
}


/************* identification of type image ************************/
int identify( s )
  unsigned char *s;
{
  int i,pos();

  for( i = 0; i < MAXTYPE; i++ )
    if( pos(s,CType[i]) >= 0 )
      return(i-(i/2)*2);

  printf("Unknown image type.\n\r");
  return(-1);
}
